package pkg

import (
	"enjoy_xxz/base"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay/pkg/jwt"
	"net/http"
	"strconv"
	"time"
)

func GetJwtToken(payload string) (string, error) {
	secretKey := "2206A"
	iat := time.Now().Unix()
	seconds := time.Now().Unix() + 86400

	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

// 解析
func Parse(tokenString string) (interface{}, error) {
	keyString := "2206A"
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (any, error) {
		return []byte(keyString), nil
	})
	if err != nil {
		fmt.Println("解析错误详情:", err) // 打印详细错误信息
		return "", fmt.Errorf("token 解析失败 >>%v", err)
	}
	if !token.Valid {
		return "", fmt.Errorf("token 失效 >>%v", err)
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		fmt.Println(claims["foo"], claims["nbf"])
		return claims["payload"], nil
	}
	return "", errors.New("token获取失败")
}

// token中间件
func JWTAuth(secretKey string) gin.HandlerFunc {
	if len(secretKey) == 0 {
		panic("secretKey 不能为空")
	}
	return func(c *gin.Context) {
		// 从请求头中获取 Token
		token := c.GetHeader("token")
		if token == "" {
			base.RespData(c, "请登录", nil)
			c.Abort()
			return
		}
		//解析token
		parse, err := Parse(token)
		if err != nil {
			base.RespData(c, "", err)
		}
		// 类型断言，确保 payload 是字符串类型
		value, ok := parse.(string)
		if !ok {
			sendUnauthorizedResponse(c, "类型断言失败")
		}
		// 将 payload 转换为用户 ID
		userID, err := strconv.Atoi(value)
		if err != nil {
			sendUnauthorizedResponse(c, "未登录")
			return
		}
		c.Set("userId", userID)
		c.Next()
	}
}

// sendUnauthorizedResponse 发送未授权响应
func sendUnauthorizedResponse(c *gin.Context, message string) {
	c.JSON(http.StatusUnauthorized, map[string]string{
		"msg": message,
	})
	c.Abort()
}

// GetAutoUserID 获取解析好的用户 ID
func GetAutoUserID(c *gin.Context) int64 {
	// 从上下文中获取用户 ID
	if value, exists := c.Get("userId"); exists {
		if userID, ok := value.(int); ok {
			fmt.Println("用户 ", userID)
			return int64(userID)
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{"message": "用户 ID 类型断言错误"})
		}
	} else {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "未获取到用户 ID"})
	}
	return 0
}
